package com.zenithsun.common.security.csrf;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.PageContext;
import javax.servlet.jsp.tagext.SimpleTagSupport;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;

/**
 * HTML form without CSRF protection 漏洞处理标签
 * @author Jiang
 */
public class TokenTagForUrl extends SimpleTagSupport {

	private static Logger log = LoggerFactory.getLogger(TokenTagForUrl.class);
	
    private String url;

    public String getUrl() {
        return url;
    }

    public void setUrl(String url) {
        this.url = url;
    }

    /**
     * 生成CSRF token Tag  for URL
     * @throws JspException
     * @throws IOException
     */
    @Override
    public void doTag() throws JspException, IOException {
        PageContext ctx = (PageContext) getJspContext();
        String token = CSRFTokenManager.createToken();
        ctx.getSession().setAttribute(CSRFTokenManager.CSRF_TOKEN_FOR_SESSION_ATTR_NAME,token);
        // CSRF token for URL
        JspWriter out = ctx.getOut();
        String paramOperate ;
        if(getUrl().indexOf("?") > 0)
        {
            paramOperate = "&";
        }else{
            paramOperate = "?";
        }
        out.print(getUrl() + paramOperate + CSRFTokenManager.CSRF_TOKEN_FOR_FORM_PARAM_NAME + "=" + token);
        log.info(getUrl() + paramOperate + CSRFTokenManager.CSRF_TOKEN_FOR_FORM_PARAM_NAME + "=" + token);
    }
}
